﻿# coding: utf-8

import os
from django.contrib.auth import authenticate
from django.http import JsonResponse
from lib.loginout import login_sys, logout_sys
from project.settings import USER_LEVEL
from services.datamodel.student.models import mm_Student, mm_StudentAgent
from django.views.decorators.csrf import csrf_exempt


class ReqHandler(object):
    def __init__(self):
        self.curDir = os.path.dirname(os.path.abspath(__file__))

    @staticmethod
    @csrf_exempt
    def loginreq(request):
        username = request.POST.get("username")
        password = request.POST.get("password")
        user = ReqHandler.student_authenticate(username=username, password=password)
        resp = {"retcode": 1}

        if user is None:
            resp["msg"] = "用户名或者密码错误!"
        elif not user.is_active:
            resp["msg"] = "用户已经被禁用"
        else:
            if user.student.level in [1, 2, 3]:
                agentObj = mm_StudentAgent.get_or_default(student_id=user.student.id)
                if agentObj.status == 0:
                    resp["msg"] = "您需要去’’优势星球app’上进行实名认证，否则不可使用后台的功能"
                    return JsonResponse(resp)
            login_sys(request, user)
            if hasattr(user, "student"):
                ut = user.student.level
                studentid = user.student.id
                share_code = user.student.share_code
            elif user.is_superuser:
                ut = USER_LEVEL.LEVEL_SUPERUSER
                studentid = 1
                share_code = 'super'
            else:
                ut = USER_LEVEL.LEVEL_NORMAL

            request.session.update({
                "ut": ut,
                "uid": user.id,
                'studentid': studentid,
                'share_code': share_code
            })
            resp["ut"] = ut
            resp["id"] = studentid
            resp["retcode"] = 0

        return JsonResponse(resp)

    @staticmethod
    def logoutreq(request):
        # logout(request)
        logout_sys(request)
        return JsonResponse({"retcode": 0})

    @staticmethod
    def student_authenticate(username, password):
        student = mm_Student.get_or_default(mobile=username)
        if student:
            if student.level in [4, 5, 6]:
                return None
            user = authenticate(username=student.user.username, password=password)
            return user
        else:
            user = authenticate(username=username, password=password)
            return user if user else None


handler = ReqHandler()
